package com.hcy.app.screen.music

import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import java.io.File
import java.io.FileOutputStream

object MusicFileManager {

    // 获取存储目录,优先使用私有外部存储空间
    fun getMusicStorageDir(context: Context):File{
        return context.getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.apply {
            mkdirs()
        }?: File(context.filesDir,Environment.DIRECTORY_MUSIC).apply { mkdirs() }
    }

    // 保存音乐文件
    fun saveMusicFile(context: Context,uri: Uri,filename: String): File?{
        return try {
            val musicDir= getMusicStorageDir(context)
            val destFile = File(musicDir,filename)
            context.contentResolver.openInputStream(uri)?.use {
                input ->
                FileOutputStream(destFile).use {
                    output ->
                    input.copyTo(output)
                }
            }
            destFile
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }
    // 保存音乐文件
    fun saveMusicFileByByte(context: Context,bs: ByteArray,filename: String){
        return try {
            val musicDir= getMusicStorageDir(context)
            val destFile = File(musicDir,filename)
            FileOutputStream(destFile).use { output ->
                output.write(bs)
            }

        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    // 获取所有音乐文件
    fun getAllMusicFiles(ctx: Context): List<String>{
        val li1 =getPublicMusicFiles(ctx)
        Log.d("HCY","getPublicMusicFiles:$li1")
        val li2 = getPrivateMusicFiles(ctx)
        return li1+li2
    }

    fun getPrivateMusicFiles(ctx: Context): List<String>{
        val audioType = setOf("mp3", "wav", "flac", "m4a") // 支持的音频格式
        val audioFiles = mutableListOf<String>()

        val musicDir= ctx.getExternalFilesDir(Environment.DIRECTORY_MUSIC)

        fun walkDir(dir: File?){
            dir?.listFiles()?.forEach { file ->
                if (file.isDirectory){
                    walkDir(file)
                }else{
                    if ( audioType.any { file.name.endsWith(it,ignoreCase = true) } ){
                        audioFiles.add(file.path)
                    }
                }
            }
        }
        walkDir(musicDir)
        return audioFiles
    }
    fun getPublicMusicFiles(ctx: Context): List<String>{
        val musicUris = mutableListOf<String>()
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DISPLAY_NAME,
            MediaStore.Audio.Media.DATA,          // 文件绝对路径
            MediaStore.Audio.Media.DURATION,       // 音乐时长（毫秒）
            MediaStore.Audio.Media.ARTIST
        )
        // 筛选音乐文件，且路径在 /Music/ 目录下
        val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0 AND ${MediaStore.Audio.Media.DATA} LIKE ?"
        val selectionArgs = arrayOf("%/Music/%")
        ctx.contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null  // 按添加时间排序
        )?.use { cursor ->
            // 处理结果
            val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
            while (cursor.moveToNext()) {
                musicUris.add(cursor.getString(pathColumn))
            }
        }
        return musicUris
    }
    // 获取音乐信息
    fun getMusicInfoByPath(context: Context, filePath: String): MusicInfo? {
        val contentResolver = context.contentResolver
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,          // 文件名（不含扩展名）
            MediaStore.Audio.Media.ARTIST,         // 歌手
            MediaStore.Audio.Media.DURATION,       // 时长（毫秒）
            MediaStore.Audio.Media.ALBUM,          // 专辑
            MediaStore.Audio.Media.DISPLAY_NAME,   // 完整文件名（含扩展名）
            MediaStore.Audio.Media.DATA            // 文件路径（用于验证）
        )

        // 通过路径筛选
        val selection = "${MediaStore.Audio.Media.DATA} = ?"
        val selectionArgs = arrayOf(filePath)

        contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null
        )?.use { cursor ->
            if (cursor.moveToFirst()) {
                return MusicInfo(
                    id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)),
                    title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)),
                    artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)),
                    duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)),
                    album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)),
                    displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)),
                    path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                )
            }
        }
        val f = File(filePath)
        return MusicInfo(
            id = 0,
            title = f.nameWithoutExtension,
            artist = "",
            duration = 0,
            album = "",
            displayName = f.name,
            path = filePath
        )
    }
}

// 数据类封装音乐信息
data class MusicInfo(
    val id: Long,
    val title: String,
    val artist: String,
    val duration: Long,
    val album: String,
    val displayName: String,
    val path: String
)
